from lxml import etree
from pyppeteer.launcher import connect
import json,requests,random,psutil,os

import urllib.parse,re,subprocess

def add_query_parameters(base_url, params):
    """
    添加查询参数到链接中，保留原始查询参数。

    Args:
        base_url (str): 基本链接。
        params (dict): 包含参数名称和值的字典。

    Returns:
        str: 包含查询参数的新链接。
    """
    # 解析基本链接以获取其查询字符串部分
    parsed_url = urllib.parse.urlparse(base_url)

    # 解析现有的查询参数
    existing_query_params = urllib.parse.parse_qs(parsed_url.query)

    # 将新参数添加到现有参数中
    existing_query_params.update(params)

    # 构建新的查询字符串
    new_query_string = urllib.parse.urlencode(existing_query_params, doseq=True)

    # 用新的查询字符串替换现有的查询字符串
    new_parsed_url = parsed_url._replace(query=new_query_string)

    # 从新的解析链接中获取最终的链接字符串
    new_url = urllib.parse.urlunparse(new_parsed_url)

    return new_url

async def repeat_goto(page,url,t=3):

    for jj in range(t):
        try:
            await page.goto(url)
            break
        except Exception as e:
            print(f'浏览器goto错误 => {e},正在重试{jj+1}次')

def get_pid_byurl(url):

    pat_pid = re.compile(r'-i[.](\d+?)[.](\d+)[?]?')
    pat_pid2 = re.compile(r'product/(\d+?)/(\d+)[/]?')
    mat = pat_pid.search(url)
    if not mat:
        mat = pat_pid2.search(url)
    if mat:
        return (mat.group(1), mat.group(2))
    else:
        return ''

async def myawait(page,xpath,t=10):

    for jj in range(t):
        try:
            s=await page.xpath(xpath)
            if s:
                return s
            await page.waitFor(1000)
        except Exception as e:
            print(f'等待xpath{xpath}错误:{jj+1}次 =>{e}')
            await page.waitFor(1000)

    return 0
def find_chrome_path():
    objcig = get_config()
    possible_paths = [
        objcig['executablePath'],
        r'C:\Program Files\Google\Chrome\Application\chrome.exe',  # 默认安装路径
        r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',  # 32位版本的默认安装路径
    ]

    for path in possible_paths:
        if os.path.exists(path):
            return path

    try:
        from winreg import ConnectRegistry, OpenKey, HKEY_LOCAL_MACHINE, QueryValue
        reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'
        with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hkey:
            with OpenKey(hkey, reg_path) as key:
                return QueryValue(key, None)
    except:
        pass

    return None

async def openChrome():
    flag=False
    try:
        session=requests.session()
        res=session.get('http://localhost:9222/json/version')
        if res.status_code==200 and res.json():
            flag=True
    except Exception as e:
        print('未启动浏览器等待启动')

    try:
        if not flag:
            exepath=find_chrome_path()
            print(exepath)
            if not exepath:
                return None
            subprocess.Popen(f'"{exepath}" --remote-debugging-port=9222 --proxy-server="http://127.0.0.1:21882"',shell=True, stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        res=session.get('http://localhost:9222/json/version')
        bobj=res.json()
        browser=await connect({
            'browserWSEndpoint':bobj['webSocketDebuggerUrl'],
            'args':['--disable-infobars','--start-maximized',
                    ],    
            'defaultViewport':None
        })
        
        return browser

    except Exception as e:
        print(e)

async def page_scroll_bottom(page,w,h,flag=False):
    
    for jj in range(3):
        await page.mouse.move(w-10,20)
        await page.mouse.down()
        await page.mouse.move(w-10,h+50, {'steps': 20})
        await page.mouse.up()
        await page.waitFor(1000)
        els=await page.xpath('//div[@data-sqe="item"]/a[1]')
        if not flag:
            if len(els)>=60:
                break
        else:
            if len(els)>=0:
                break
def kchrome():
    pids = psutil.pids()
    for pid in pids:
        try:
            p = psutil.Process(pid)
            # print('pid-%s,pname-%s' % (pid, p.name()))
            if p.name() == 'chrome.exe':
                #print(f'关闭{pid} => {p.name()}')
                cmd = 'taskkill /F /IM chrome.exe'
                os.system(cmd)

        except Exception as e:
            pass

def killjc(jcname):
    pids = psutil.pids()
    for pid in pids:
        try:
            p = psutil.Process(pid)
            # print('pid-%s,pname-%s' % (pid, p.name()))
            if p.name() == f'{jcname}':
                print(f'关闭{pid} => {p.name()}')
                cmd = f'taskkill /F /IM {jcname}'
                os.system(cmd)

        except Exception as e:
            pass
     
def get_config(path='config.json'): 
    with open(path,'rb') as f:
        objcig=json.load(f)
    return objcig

session=requests.session()
async def ghkkkk(page):
    obj=get_config()
    cot= await page.content()
    img0=etree.HTML(cot).xpath('//img[@class="Yj2cCM"]/@src')[0]
    img1=etree.HTML(cot).xpath('//img[@class="gQ7PIj"]/@src')[0]

    url='http://api.jfbym.com/api/YmServer/customApi'

    data={
        'slide_image':img1,
        'background_image':img0,
        'token':obj['token'],
        'type':'20111'
    }
    res=session.post(url,data=data)
    obj=res.json()
    distance=int(obj['data']['data'])
    print(f'滑行距离{distance}')
    el = (await page.xpath('//*[@class="hAeNxI"]'))[0]
    elhk=(await page.xpath('//*[@class="gQ7PIj"]'))[0]
    box = await el.boundingBox()
    boxhk=await elhk.boundingBox()
    await page.hover('.hAeNxI')
    await page.mouse.down()
    await page.mouse.move(box['x'] + distance+boxhk['width']/2-10, box['y'] + 5,{'delay': 5000, 'steps': random.randint(100, 200)})
    await page.mouse.up()
